﻿using LDM.Framework.Application;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Winton.Extensions.Configuration.Consul;

namespace LDM.Framework.Conul
{
    public static class ConsulServiceExtensions
    {
        /// <summary>
        /// 添加异常处理服务扩展服务
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static void AddConsulConfigure(this IServiceCollection services)
        {
            services.Configure<ConsulClientOptions>(App.Configuration.GetSection("ConsulClientOptions"));
            services.AddConsulDispatcher(ConsulDispatcherType.Polling);
        }

        /// <summary>
        /// 添加Consul配置中心
        /// </summary>
        /// <param name="hostBuilder"></param>
        public static void AddConsulConfig(this IWebHostBuilder hostBuilder) 
        {
            hostBuilder.ConfigureAppConfiguration((hostContext, config) =>
            {
                var env = hostContext.HostingEnvironment;
                hostContext.Configuration = config.Build();
                string consul_url = hostContext.Configuration["Consul:Address"];
                string consul_ConfigKey = hostContext.Configuration["Consul:ConsulConfigKey"];
                var configKeyDocs = consul_ConfigKey.Split(",");
                foreach (var configKey in configKeyDocs)
                {
                    config.AddConsul(
                          //$"{env.ApplicationName}/appsettings.{env.EnvironmentName}.json",
                          configKey,
                          options =>
                          {
                              //配置热更新 动态加载
                              options.ReloadOnChange = true;
                              options.Optional = true;
                              options.OnLoadException = exceptionContext => { exceptionContext.Ignore = true; };
                              options.ConsulConfigurationOptions = cco => { cco.Address = new Uri(consul_url); };
                          });
                }
                hostContext.Configuration = config.Build();
            });
        }
    }
}
